import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, LoginRequest } from '@/types'
import { authAPI } from '@/api'

export const useAuthStore = defineStore('auth', () => {
  // State
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('auth_token'))
  const loading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const userPermissions = computed(() => user.value?.permissions || [])
  const userRole = computed(() => user.value?.role || '')

  // Helper function to check permissions
  const hasPermission = (permission: string): boolean => {
    return userPermissions.value.includes(permission) || userPermissions.value.includes('*')
  }

  const hasAnyPermission = (permissions: string[]): boolean => {
    return permissions.some(permission => hasPermission(permission))
  }

  const hasRole = (role: string): boolean => {
    return userRole.value === role || userRole.value === 'admin'
  }

  // Actions
  const login = async (credentials: LoginRequest) => {
    loading.value = true
    error.value = null

    try {
      const response = await authAPI.login(credentials)
      
      if (response.success) {
        token.value = response.data.token
        user.value = {
          ...response.data.user,
          permissions: response.data.permissions // 正确保存权限数据
        }
        
        // 安全地存储到 localStorage
        if (response.data.token && user.value) {
          localStorage.setItem('auth_token', response.data.token)
          localStorage.setItem('user_info', JSON.stringify(user.value))
        } else {
          console.error('⚠️ 警告：响应数据不完整，无法存储到 localStorage')
        }
        
        console.log('Login successful, user authenticated:', !!user.value, 'token:', !!token.value)
        console.log('User permissions:', user.value.permissions)
        
        return { success: true, message: response.message }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err: any) {
      const message = err.response?.data?.message || '登录失败，请重试'
      error.value = message
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  const logout = async (force = false) => {
    if (!force) {
      console.log('🔄 正常登出流程')
    } else {
      console.log('⚠️ 强制登出 - 可能是认证失败')
    }
    
    loading.value = true
    
    try {
      // Call logout API only if not forced logout
      if (!force) {
        await authAPI.logout()
      }
    } catch (err) {
      console.warn('登出API调用失败:', err)
    } finally {
      // Clear state regardless of API call result
      user.value = null
      token.value = null
      error.value = null
      
      // Clear localStorage
      localStorage.removeItem('auth_token')
      localStorage.removeItem('user_info')
      localStorage.removeItem('current_session_id')
      
      loading.value = false
      console.log('✅ 登出完成，数据已清理')
    }
  }

  const getCurrentUser = async () => {
    if (!token.value) return false

    loading.value = true
    
    try {
      const response = await authAPI.getCurrentUser()
      
      if (response.success && response.data) {
        user.value = {
          ...response.data.user,
          permissions: response.data.permissions // 正确保存权限数据
        }
        
        // 安全地存储到 localStorage
        if (user.value) {
          localStorage.setItem('user_info', JSON.stringify(user.value))
        } else {
          console.error('⚠️ 警告：用户数据不完整，无法存储到 localStorage')
        }
        return true
      } else {
        // Token invalid, logout silently
        await logout(true)
        return false
      }
    } catch (err) {
      console.error('获取用户信息失败:', err)
      await logout(true)
      return false
    } finally {
      loading.value = false
    }
  }

  // 验证当前token是否有效
  const validateToken = async (silent = true) => {
    try {
      if (!token.value) {
        if (!silent) console.log('❌ 没有token')
        return false
      }
      
      // 尝试获取用户信息来验证token
      const isValid = await getCurrentUser()
      if (isValid) {
        if (!silent) console.log('✅ Token验证通过')
      } else {
        if (!silent) console.log('❌ Token验证失败')
      }
      return isValid
    } catch (err: any) {
      if (!silent) console.error('Token验证异常:', err)
      // 只有在明确401错误时才清理认证状态
      // 其他错误（如网络错误）不应该强制登出
      if (err.response?.status === 401) {
        logout()
      }
      return false
    }
  }

  const changePassword = async (oldPassword: string, newPassword: string) => {
    loading.value = true
    error.value = null

    try {
      const response = await authAPI.changePassword({ oldPassword, newPassword })
      
      if (response.success) {
        return { success: true, message: response.message }
      } else {
        error.value = response.message
        return { success: false, message: response.message }
      }
    } catch (err: any) {
      const message = err.response?.data?.message || '修改密码失败'
      error.value = message
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  const updateUserProfile = (userData: Partial<User>) => {
    if (user.value) {
      user.value = { ...user.value, ...userData }
      
      // 安全地存储到 localStorage
      if (user.value) {
        localStorage.setItem('user_info', JSON.stringify(user.value))
      } else {
        console.error('⚠️ 警告：更新后的用户数据不完整')
      }
    }
  }

  // Initialize store
  const initialize = async () => {
    const storedUser = localStorage.getItem('user_info')
    
    if (token.value && storedUser) {
      try {
        // 安全的 JSON 解析，检查是否为有效的 JSON 字符串
        if (storedUser === 'undefined' || storedUser === 'null' || !storedUser.trim()) {
          console.log('🧹 清理无效的用户信息存储')
          localStorage.removeItem('user_info')
          localStorage.removeItem('auth_token')
          token.value = null
          user.value = null
          return
        }
        
        user.value = JSON.parse(storedUser)
        console.log('✅ 恢复用户状态:', user.value?.username)
        
        // Verify token is still valid by fetching current user (non-blocking)
        const isValid = await getCurrentUser()
        if (!isValid) {
          console.log('⚠️ Token已失效，需要重新登录')
        }
      } catch (err) {
        console.error('❌ 初始化认证状态失败:', err)
        console.log('🧹 清理损坏的认证数据')
        // 清理损坏的数据
        localStorage.removeItem('user_info')
        localStorage.removeItem('auth_token')
        user.value = null
        token.value = null
      }
    } else {
      // 没有有效的认证数据
      user.value = null
      token.value = null
    }
  }

  const clearError = () => {
    error.value = null
  }

  return {
    // State
    user,
    token,
    loading,
    error,
    
    // Getters
    isAuthenticated,
    userPermissions,
    userRole,
    
    // Permission helpers
    hasPermission,
    hasAnyPermission,
    hasRole,
    
    // Actions
    login,
    logout,
    getCurrentUser,
    validateToken,
    changePassword,
    updateUserProfile,
    initialize,
    clearError
  }
})
